package com.swb.alibaba.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>文件  ValidatorUtil</p>
 * <p>时间  2021-06-30 23:05:13</p>
 *
 * @author swb
 */
public class ValidatorUtil {
    private static final String REGEX_MOBILE = "^(1[0-9][0-9])\\d{8}$";
    private static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    private static final String REGEX_ID_CARD = "^\\d{15}|^\\d{17}([0-9]|X|x)$";
    private static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
    private static final String REGEX_URL2 = "([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";

    private ValidatorUtil() {
    }

    public static boolean isMobile(String mobile) {
        return Pattern.matches("^(1[0-9][0-9])\\d{8}$", mobile);
    }

    public static boolean isEmail(String email) {
        return Pattern.matches("^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", email);
    }

    public static boolean isIDCard(String idCard) {
        boolean flag = false;
        if (Pattern.matches("^\\d{15}|^\\d{17}([0-9]|X|x)$", idCard)) {
            flag = checkIDCard(idCard);
        }

        return flag;
    }

    public static boolean isUrl(String url) {
        boolean flag;
        if (Pattern.matches("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?", url)) {
            flag = true;
        } else {
            flag = Pattern.matches("([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?", url);
        }

        return flag;
    }

    private static boolean checkIDCard(String idCard) {
        boolean result = false;
        int[] powers = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        Map<Integer, String> parityBit = new HashMap();
        parityBit.put(0, "1");
        parityBit.put(1, "0");
        parityBit.put(2, "X");
        parityBit.put(3, "9");
        parityBit.put(4, "8");
        parityBit.put(5, "7");
        parityBit.put(6, "6");
        parityBit.put(7, "5");
        parityBit.put(8, "4");
        parityBit.put(9, "3");
        parityBit.put(10, "2");
        int sum = 0;
        int len = idCard.length();

        int mode;
        for(mode = 0; mode < len - 1; ++mode) {
            sum += Integer.parseInt(String.valueOf(idCard.charAt(mode))) * powers[mode];
        }

        mode = sum % 11;
        if (((String)parityBit.get(mode)).equals(String.valueOf(idCard.charAt(len - 1)))) {
            result = true;
        }

        return result;
    }
}
